package v1

import (
	"chat/internal/common/response"
	"chat/internal/model"
	"chat/internal/service"
	"chat/pkg/util"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"net/http"
	"strconv"
)

func Login(c *gin.Context) {
	var user model.User
	c.ShouldBind(&user)

	queryUser, err := service.GetUserByPhone(&user)

	if err == nil && util.ValidatePasswords(queryUser.Password, []byte(user.Password)) {
		queryUser.Password = ""
		c.JSON(http.StatusOK, response.SuccessMsg(queryUser))
		return
	}
	if err == gorm.ErrRecordNotFound {
		c.JSON(http.StatusOK, response.FailMsg("用户不存在"))
		return
	}
	c.JSON(http.StatusOK, response.FailMsg("密码错误"))
}

func GetUserInfo(c *gin.Context) {
	idStr, ok := c.GetQuery("id")
	id, _ := strconv.Atoi(idStr)
	if !ok {
		c.JSON(http.StatusOK, response.FailMsg("参数获取失败"))
		return
	}

	user, err := service.GetUserInfo(id)

	if err == nil {
		c.JSON(http.StatusOK, response.SuccessMsg(user))
		return
	}
	c.JSON(http.StatusOK, response.FailMsg("GetUserInfo error"))
}

func GetLinkedInfoList(c *gin.Context) {
	idStr, ok := c.GetQuery("uid")
	id, _ := strconv.Atoi(idStr)
	if !ok {
		c.JSON(http.StatusOK, response.FailMsg("参数获取失败"))
		return
	}
	list, err := service.GetLinkedInfoList(id)

	if err == nil {
		c.JSON(http.StatusOK, response.SuccessMsg(list))
		return
	}
	c.JSON(http.StatusOK, response.FailMsg("GetLinkedInfoList error"))
	return
}

func UpdateUserInfo(c *gin.Context) {
	var user model.User
	c.ShouldBindJSON(&user)
	err := service.UpdateUserInfo(user)
	if err == nil {
		c.JSON(http.StatusOK, response.SuccessMsg(nil))
		return
	}
	c.JSON(http.StatusOK, response.FailMsg("UpdateUserInfo error"))
	return
}

func SignUp(c *gin.Context) {
	var user model.User
	c.ShouldBind(&user)
	// 检查手机号是否注册过
	cnt, err := service.GetUserNumByPhone(user.Phone)
	if err != nil {
		c.JSON(http.StatusInternalServerError, response.FailMsg("服务端异常"))
		return
	}
	if cnt > 0 {
		c.JSON(http.StatusOK, response.FailMsg("改手机号已经注册过"))
		return
	}
	user.Password = util.HashAndSalt([]byte(user.Password))
	err = service.CreateUser(&user)

	if err != nil {
		c.JSON(http.StatusInternalServerError, response.FailMsg("服务端异常"))
		return
	}
	c.JSON(http.StatusOK, response.SuccessMsg(nil))
}

func GetChatUserListByUserId(c *gin.Context) {
	idStr, ok := c.GetQuery("id")
	id, _ := strconv.Atoi(idStr)
	if !ok {
		c.JSON(http.StatusOK, response.FailMsg("参数获取失败"))
		return
	}
	var v []response.ChatInfo
	list, err := service.GetFriendsInfoByUserId(id)
	if err == nil {
		for _, e := range list {
			v = append(v, response.ChatInfo{
				User:   e.Nickname,
				UserId: e.Id,
				Url:    e.Avatar,
				Type:   1,
			})
		}
	}
	list1, err := service.GetGroupsChatInfoByUserId(id)
	if err == nil {
		for _, e := range list1 {
			v = append(v, response.ChatInfo{
				User:   e.Name,
				UserId: e.ID,
				Url:    "https://lishuangzhi-beijing.oss-cn-beijing.aliyuncs.com/img/qun.png",
				Type:   2,
			})
		}
	}
	c.JSON(http.StatusOK, response.SuccessMsg(v))
	return

}
